<template>
  <a-modal
    :maskClosable="false"
    :title="title"
    centered
    :width="600"
    v-model="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
  >
    <a-form :form="form">
      <a-form-item
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        label="上级组织"
      >
        <a-tree-select
          :disabled="type === 'edit'"
          :tree-data="option"
          placeholder="请选择上级组织"
          tree-default-expand-all
          :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
          v-decorator="['parentId', {rules: [{ required: true, message: '请选择上级组织' }]}]">
        </a-tree-select>
      </a-form-item>
      <a-form-item
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        label="名称"
      >
        <a-input placeholder="请输入名称" v-decorator="['deptName', {rules: [{ required: true, message: '请输入名称' }]}]" />
        <a-input v-decorator="['deptId']" hidden></a-input>
      </a-form-item>
      <a-form-item
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        label="成立日期"
      >
        <a-date-picker
          format="YYYY-MM-DD"
          style="width: 100%;"
          valueFormat="YYYY-MM-DD"
          :disabled-date="disabledDate"
          v-decorator="['establishDate', {rules: [{ required: true, message: '请选择成立时间' }]}]"
        />
      </a-form-item>
      <a-form-item
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        label="地区"
      >
        <div class="city-box">
          <a-input hidden v-decorator="['areaIds', {rules: [{ required: true, message: '请选择地区' }]}]"></a-input>
          <a-input hidden v-decorator="['area']"></a-input>
          <a-select placeholder="省" style="width: 30%;margin-right: 4%;" :defaultValue="1" v-decorator="['provinceId']" @change="handleGetDistList($event, 'city')">
            <a-select-option :value="item.id" v-for="(item, index) in provinceOption" :key="index">{{ item.extName }}</a-select-option>
          </a-select>
          <a-select
            placeholder="市"
            style="width: 30%;margin-right: 4%;"
            v-decorator="['cityId']"
            @change="handleGetDistList($event, 'area')">
            <a-select-option :value="item.id" v-for="(item, index) in cityOption" :key="index">{{ item.extName }}</a-select-option>
          </a-select>
          <a-select
            placeholder="区"
            style="width: 30%;"
            v-decorator="['areaId']"
            @change="handleAddareaIds">
            <a-select-option :value="item.id" v-for="(item, index) in areaOption" :key="index">{{ item.extName }}</a-select-option>
          </a-select>
        </div>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script>
import { orgCreate, deptEdit, getDistList } from '@/api/system/system'
import moment from 'moment'
import pick from 'lodash.pick'
export default {
  components: {
  },
  data () {
    return {
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      form: this.$form.createForm(this),
      title: '',
      type: '',
      option: [],
      provinceOption: [],
      cityOption: [],
      areaOption: []
    }
  },
  beforeCreate () {
  },
  created () {
  },
  methods: {
    moment,
    disabledDate (current) { return current && current >= this.moment().endOf('day') },
    add (obj) {
      this.title = obj.title
      this.type = obj.type
      this.option = obj.option
      this.visible = true
      this.handleGetDistList('0', 'province')
      this.$nextTick(() => {
        this.form.resetFields()
      })
    },

    edit (obj) {
      this.title = obj.title
      this.type = obj.type
      this.option = obj.option
      this.handleGetDistList('0', 'province')
      var areaArr = []
      if (obj.data.areaIds) {
        areaArr = obj.data.areaIds.split(',')
        this.handleGetDistList(areaArr[0], 'city', true, areaArr[1])
        this.handleGetDistList(areaArr[1], 'area', true, areaArr[2])
      }
      this.visible = true
      this.$nextTick(() => {
        if (areaArr.length > 0) {
          this.form.setFieldsValue({ 'provinceId': Number(areaArr[0]), 'cityId': Number(areaArr[1]), 'areaId': Number(areaArr[2]) })
        }
        this.form.setFieldsValue(pick(obj.data, 'deptId', 'deptName', 'parentId', 'area', 'areaIds', 'establishDate'))
      })
    },

    // 获取城市
    handleGetDistList (id, type, flag, val) {
      var params = {
        pid: id
      }
      if (!flag) {
        switch (type) {
          case 'province':
            this.form.setFieldsValue({ 'provinceId': undefined, 'cityId': undefined, 'areaId': undefined })
            this.provinceOption = []
            this.cityOption = []
            this.areaOption = []
            break
          case 'city':
            this.form.setFieldsValue({ 'cityId': undefined, 'areaId': undefined })
            this.areaOption = []
            break
          case 'area':
            this.form.setFieldsValue({ 'areaId': undefined })
            break
        }
      }
      return getDistList(params).then(res => {
        if (res.code === 0) {
          switch (type) {
            case 'province':
              this.provinceOption = JSON.parse(JSON.stringify(res.rows))
              break
            case 'city':
              this.cityOption = JSON.parse(JSON.stringify(res.rows))
              if (flag) {
                this.$nextTick(() => {
                  this.form.setFieldsValue({ 'cityId': Number(val) })
                })
              }
              break
            case 'area':
              this.areaOption = JSON.parse(JSON.stringify(res.rows))
              if (flag) {
                this.$nextTick(() => {
                  this.form.setFieldsValue({ 'areaId': Number(val) })
                })
              }
              break
          }
        }
      })
    },

    // 赋值地址
    handleAddareaIds (e) {
      var provinceName = ''
      var cityName = ''
      var areaName = ''
      for (var provinceItem of this.provinceOption) {
        if (provinceItem.id === this.form.getFieldValue('provinceId')) {
          provinceName = provinceItem.extName
        }
      }
      for (var cityItem of this.cityOption) {
        if (cityItem.id === this.form.getFieldValue('cityId')) {
          cityName = cityItem.extName
        }
      }
      for (var areaItem of this.areaOption) {
        if (areaItem.id === e) {
          areaName = areaItem.extName
        }
      }
      this.form.setFieldsValue({ 'area': provinceName + cityName + areaName })
      this.form.setFieldsValue({ 'areaIds': this.form.getFieldValue('provinceId') + ',' + this.form.getFieldValue('cityId') + ',' + e })
    },

    handleSubmit (e) {
      var _this = this
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          var data = JSON.parse(JSON.stringify(values))
          if (_this.type === 'add') {
            return orgCreate(data).then(res => {
              _this.$message.success('新增成功', 1)
              _this.visible = false
              _this.$emit('ok')
            }).finally(() => {
              _this.confirmLoading = false
            })
          } else {
            return deptEdit(data).then(res => {
              _this.$message.success('编辑成功', 1)
              _this.visible = false
              _this.$emit('ok')
            }).finally(() => {
              _this.confirmLoading = false
            })
          }
        }
      })
    }
  }
}
</script>
<style scoped>
  .city-box{
  }
</style>
